/*
 * @description 用户方 - 仪表盘
 * @fileName userindex.js
 * @date 2025/07/24 21:45:53
 */

/**
 * 初始化 最新公告 流程
 */
const initializationNotifyContect = function () {
  const $ = layui.$
  let notifyList = []

  /**
   * 系统公告 接口
   */
  function getSystemNotify(callback) {
    // const $ = layui.$
    const URL = '/app/admin/v1-api/getNoticeList'
    layer.load()
    $.ajax({
      url: URL,
      type: 'GET',
      data: {},
      success: function (res) {
        layer.closeAll('loading')
        if (res.code) {
          layui.popup.failure(res.msg)
          return
        }
        callback && callback(res.data || [])
      },
    })
  }

  // 查看公告详情
  $('.notice-list').on('click', 'li', function (event) {
    const id = $($(this).context).attr('data-id')
    const idx = notifyList.findIndex((item) => item.id == id)
    if (idx >= 0) openNotify(notifyList[idx])
  })

  const renderNotifyElement = (list) => {
    notifyList = [...list]
    const fragment = new DocumentFragment()
    $.each(list, function (index, item) {
      fragment.appendChild(
        $(`<li data-id="${item.id}">
            <div class="notice__title">${item.title}</div>
            <div class="notice__time flex align-center">
              <i class="pear-icon pear-icon-time"></i
              ><span>${item.created_at}</span>
            </div>
          </li>`)[0]
      )
    })
    $('.notice-list').html(fragment)
  }

  // 获取系统公告
  getSystemNotify(renderNotifyElement)
}

/**
 * 我的价格
 */
function CustomMyPicre() {
  return {
    cols: [
      [
        {
          title: '产品',
          field: 'name',
          width: 250,
        },
        { field: 'rp', title: '日卡', align: 'center' },
        { field: 'zp', title: '周卡', align: 'center' },
        { field: 'yp1', title: '月卡', align: 'center' },
        { field: 'yp3', title: '季卡', align: 'center' },
        { field: 'yp6', title: '半年卡', align: 'center' },
        { field: 'np', title: '年卡', align: 'center' },
      ],
    ],
  }
}

// 自定义价格链接
function CustomLinkPrice() {
  const $ = layui.$
  return {
    getCols: function () {
      return [
        [
          {
            field: 'remark',
            title: '备注',
            width: 120,
          },
          {
            field: 'link',
            title: '推广链接',
            // templet: function (d) {
            //   return `${window.location.origin}${d.link}`
            // },
          },
          {
            title: '操作',
            templet: '#toolEvent',
            align: 'center',
            width: 220,
          },
        ],
      ]
    },

    /**
     * 删除自定义推广链接
     * @param {string} id 推广链接
     * @param {Function} callback callback
     */
    removeLink: function (id, callback) {
      const URL = `/app/admin/v1-api/deleteLink?id=${id}`
      layer.load()
      $.ajax({
        url: URL,
        type: 'GET',
        success: function (res) {
          layer.closeAll('loading')
          if (res.code) {
            layer.msg(res.msg)
            return
          }
          callback && callback()
        },
      })
    },
    renderTabHeader: function (list) {
      const fragment = new DocumentFragment()
      $.each(list, function (index, item) {
        fragment.append(
          $(
            `<li class="${index === 0 ? 'layui-this' : ''}">${item.name}</li>`
          )[0]
        )
      })
      $('#promotion-tab').html(fragment)
    },

    renderRemark: function (remark = undefined) {
      $('#remark').val(remark)
    },

    // 渲染 推广设置 内送区域
    renderTabContact: function (
      emptyList = [],
      dataList = [],
      rowId = undefined
    ) {
      const form = layui.form
      const fragment = new DocumentFragment()
      const $parent = $('#promotion-tab-contact')

      $.each(emptyList, function (index, _item) {
        let item = Object.assign({}, _item)

        // 如果是编辑执行
        if (dataList && dataList.length) {
          const temps = dataList.find((item) => item.line_id === _item.line_id)
          if (temps) {
            const keys = [
              'rp_show',
              'zp_show',
              'yp1_show',
              'yp3_show',
              'yp6_show',
              'np_show',
            ]
            const vals = keys.reduce(
              (pre, key) => ({
                ...pre,
                [key]: _item[key],
              }),
              {}
            )
            item = Object.assign({}, _item, temps, vals)
          }
        }

        fragment.append(
          $(`<div class="layui-tab-item ${index === 0 ? 'layui-show' : ''}">
          <form class="layui-form" lay-filter="promotion_${index}" data-id="${
            item.line_id
          }">
            <input type="hidden" name="rp_show" value="${item.rp_show}" />
            <input type="hidden" name="zp_show" value="${item.zp_show}" />
            <input type="hidden" name="yp1_show" value="${item.yp1_show}" />
            <input type="hidden" name="yp3_show" value="${item.yp3_show}" />
            <input type="hidden" name="yp6_show" value="${item.yp6_show}" />
            <input type="hidden" name="np_show" value="${item.np_show}" />

            <!-- 测试卡数量 -->
            <div class="layui-form-item">
              <div class="layui-form-label">测试卡数量</div>
              <div class="layui-input-block">
                <input
                  name="test_number"
                  type="number"
                  min="0"
                  placeholder="请输入测试卡数量"
                  autocomplete="off"
                  class="layui-input"
                  value="${item.test_number ?? ''}"
                />
              </div>
            </div>

            <!-- 最大调换数量 -->
            <div class="layui-form-item">
              <div class="layui-form-label">最大调换数量</div>
              <div class="layui-input-block">
                <input
                  name="max_exchange_number"
                  type="number"
                  min="0"
                  max=${_item.max_exchange_number ?? 999}
                  placeholder="请输入最大调换数量"
                  autocomplete="off"
                  class="layui-input"
                  value="${item.max_exchange_number ?? ''}"
                />
              </div>
            </div>

            <!-- 日卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.rp_show == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">日卡</div>
              <div class="layui-input-block">
                <div class="crow">
                  <input
                    name="rp"
                    type="number"
                    min="${_item.rp ?? 0}"
                    placeholder="请输入日卡价格"
                    autocomplete="off"
                    class="layui-input"
                    value="${item.rp ?? ''}"
                  />
<!--                  <span>官方价格：${_item.rp_official ?? 0}</span>-->
                </div>
              </div>
            </div>

            <!-- 周卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.zp_show == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">周卡</div>
              <div class="layui-input-block">
                <div class="crow">
                  <input
                    name="zp"
                    type="number"
                    min="${_item.zp ?? 0}"
                    placeholder="请输入周卡价格"
                    autocomplete="off"
                    class="layui-input"
                    value="${item.zp ?? ''}"
                  />
<!--                  <span>官方价格：${_item.zp_official ?? 0}</span>-->
                </div>
              </div>
            </div>

            <!-- 月卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.yp1_show == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">月卡</div>
              <div class="layui-input-block">
                <div class="crow">
                  <input
                    type="number"
                    name="yp1"
                    min="${_item.yp1 ?? 0}"
                    placeholder="请输入月卡价格"
                    autocomplete="off"
                    class="layui-input"
                    value="${item.yp1 ?? ''}"
                  />
<!--                  <span>官方价格：${_item.yp1_official ?? 0}</span>-->
                </div>
              </div>
            </div>

            <!-- 季卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.yp3_show == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">季卡</div>
              <div class="layui-input-block">
                <div class="crow">
                  <input
                    type="number"
                    name="yp3"
                    min="${_item.yp3 ?? 0}"
                    placeholder="请输入月卡价格"
                    autocomplete="off"
                    class="layui-input"
                    value="${item.yp3 ?? ''}"
                  />
<!--                  <span>官方价格：${_item.yp3_official ?? 0}</span>-->
                </div>
              </div>
            </div>

            <!-- 半年卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.yp6_show == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">半年卡</div>
              <div class="layui-input-block">
                <div class="crow">
                  <input
                    type="number"
                    name="yp6"
                    min="${_item.yp6 ?? 0}"
                    placeholder="请输入半年卡价格"
                    autocomplete="off"
                    class="layui-input"
                    value="${item.yp6 ?? ''}"
                  />
<!--                  <span>官方价格：${_item.yp6_official ?? 0}</span>-->
                </div>
              </div>
            </div>
 
            <!-- 年卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.np_show == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">年卡</div>
              <div class="layui-input-block">
                <div class="crow">
                  <input
                    type="number"
                    name="np"
                    min="${_item.np ?? 0}"
                    placeholder="请输入年卡价格"
                    autocomplete="off"
                    class="layui-input"
                    value="${item.np ?? ''}"
                  />
<!--                  <span>官方价格：${_item.np_official ?? 0}</span>-->
                </div>
              </div>
            </div>

            <!-- ====== -->

            <!-- 允许开日卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.rp_show == '1' && _item.rp_switch == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">允许开日卡</div>
              <div class="layui-input-block">
                <input type="checkbox" name="rp_switch" lay-skin="switch"
                ${item.rp_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>

            <!-- 允许开周卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.zp_show == '1' && _item.zp_switch == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">允许开周卡</div>
              <div class="layui-input-block">
                <input type="checkbox" name="zp_switch" lay-skin="switch"
                ${item.zp_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>

            <!-- 允许开月卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.yp1_show == '1' && _item.yp1_switch == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">允许开月卡</div>
              <div class="layui-input-block">
                <input type="checkbox" name="yp1_switch" lay-skin="switch" 
                ${item.yp1_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>

            <!-- 允许开季卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.yp3_show == '1' && _item.yp3_switch == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">允许开季卡</div>
              <div class="layui-input-block">
                <input type="checkbox" name="yp3_switch" lay-skin="switch"
                  ${item.yp3_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>

            <!-- 是否允许开半年卡 -->
            <div class="layui-form-item" 
              style="display: ${
                item.yp6_show == '1' && _item.yp6_switch == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">允许开半年卡</div>
              <div class="layui-input-block">
                <input type="checkbox" name="yp6_switch" lay-skin="switch"
                  ${item.yp6_switch == '1' ? 'checked' : ''}
                 />
              </div>
            </div>

            <!-- 是否允许开年卡 -->
            <div class="layui-form-item" 
              style="display: ${
                item.np_show == '1' && _item.np_switch == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">允许开年卡</div>
              <div class="layui-input-block">
                <input type="checkbox" name="np_switch" lay-skin="switch"
                  ${item.np_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>
            <div class="layui-form-item">
              <div class="layui-input-block">
                <div class="tips">
                  <i
                    >我的价格：月卡 <span>${_item.yp1}</span> 金币 周卡
                    <span>${_item.zp}</span> 金币 天卡 <span>${
            _item.rp
          }</span> 金币</i
                  >
                </div>
              </div>
            </div>
          </form></div>`)[0]
        )
      })

      $parent.html(fragment)
      if (rowId) {
        $('#remark').attr('data-row-id', rowId)
      }
      setTimeout(function () {
        // 渲染 form tab - switch element.
        form.render() // 渲染全部
      }, 60)
    },

    // 格式化表单数据 处理 `switch` on|off 问题
    formatFormData: function (formData) {
      // 额外处理 switch 字段
      const keys = [
        'rp_switch',
        'zp_switch',
        'yp1_switch',
        'yp3_switch',
        'yp6_switch',
        'np_switch',
      ]

      for (const key of keys) {
        if (key in formData) {
          const value = formData[key]
          if (['on', 'off'].includes(value)) {
            formData[key] = value === 'on' ? '1' : '0'
          } else continue
        } else {
          formData[key] = '0'
        }
      }

      return formData
    },

    // 保存当前表单
    saveCurrentForm: function (callback) {
      const _that = this
      const form = layui.form
      let rowId = $('#remark').attr('data-row-id')

      const getFormAttrStr = (formElement, key = 'lay-filter') =>
        $(formElement).attr(key)
      const datas = [] // 过滤的 `formDatas`

      // 获取所有的 tab-contact/
      const $parentTabItems = $('#promotion-tab-contact .layui-tab-item')
      $.each($parentTabItems, function (index, item) {
        const formElement = $(item).find('form')[0]
        const filterStr = getFormAttrStr(formElement)
        const line_id = getFormAttrStr(formElement, 'data-id')
        const formData = _that.formatFormData(form.val(filterStr))
        datas.push(Object.assign(formData, { line_id }))
      })

      const remark = $('#remark').val()

      if (!remark) return layer.msg('请输入备注')

      layer.confirm('确认保存, 是否继续?', function (index) {
        _that.saveFormData(rowId, remark, datas, function () {
          layer.close(index)
          callback && callback()
          $('#remark').attr('data-row-id', '') // 清空备注上的Id
        })
      })
    },
    saveFormData: function (id, remark, datas, callback) {
      // ?id=0&remark=测试测试&data=[{"line_id":1,"test_number":2,"test_switch":1,"test2h_switch":1,"test6h_switch":1,"test12h_switch":1,"max_exchange_number":200,"rp":"2","zp":"3","yp1":"5","yp3":"15","yp6":"30","np":"60","rp_switch":1,"zp_switch":1,"yp1_switch":1,"yp3_switch":1,"yp6_switch":1,"np_switch":1},{"line_id":2,"test_number":2,"test_switch":1,"test2h_switch":1,"test6h_switch":1,"test12h_switch":1,"max_exchange_number":200,"rp":"3","zp":"4","yp1":"5","yp3":"15","yp6":"30","np":"60","rp_switch":1,"zp_switch":1,"yp1_switch":1,"yp3_switch":1,"yp6_switch":1,"np_switch":1}]
      let URL = `/app/admin/v1-api/createLink`
      const params = [`remark=${remark}`, `data=${JSON.stringify(datas)}`]
      if (id) params.push(`id=${id}`)
      URL += `?${params.join('&')}`

      layer.load()
      $.ajax({
        url: URL,
        type: 'GET',
        success: function (res) {
          layer.closeAll('loading')
          if (res.code) {
            layer.msg(res.msg)
            return
          }
          layer.msg(res.msg)
          callback && callback()
        },
      })
    },
  }
}

function CustomIndexModify() {
  const $ = layui.$
  const layer = layui.layer
  return {
    // 获取首页信息
    getInfo: function (callback) {
      const URL = '/app/admin/v1-api/getIndex' // 首页接口
      layer.load()
      $.ajax({
        url: URL,
        type: 'GET',
        data: {},
        success: function (res) {
          layer.closeAll('loading')
          if (res.code) {
            layui.popup.failure(res.msg)
            return
          }
          callback && callback(res.data || {})
        },
      })
    },

    // 渲染节点购买信息
    renderNodesInfo: function (list, infos) {
      const $parent = $('.product-wrapper')
      const fragment = new DocumentFragment()
      $.each(list, function (index, item) {
        // test_used_number 缺少 测试使用数量
        // useexchangenum 缺少 调换已使用数量
        // NOTE: 以添加、不知道正确与否
        fragment.appendChild(
          $(`
            <div class="layui-col-md3">
              <div class="layui-card">
                <div class="layui-card-header">${item.name}</div>
                <div class="layui-card-body">
                  <ul class="product-info">
                    <li>
                      <strong>${infos.valid_data[item.line_id] ?? 0}</strong>
                      <span>有效数量</span>
                    </li>
                    <li>
                      <strong>${infos.expire_data[item.line_id] ?? 0}</strong>
                      <span>过期数量</span>
                    </li>
                    <li>
                      <strong>${item.test_number ?? 0}/${
            infos.text_user_data[item.line_id] ?? 0
          }</strong>
                      <span>测试数量</span>
                    </li>
                    <li>
                      <strong>${item.max_exchange_number ?? 0}/${
            infos.exchange_user_data[item.line_id] ?? 0
          }</strong>
                      <span>调换数量</span>
                    </li>
                    <li>
                      <strong>${item.order_node_refund_time ?? 0}</strong>
                      <span>退款时间/小时</span>
                    </li>
                    <li>
                      <strong>${item.order_node_refund_number ?? 0}/${
            infos.refund_user_data[item.line_id] ?? 0
          }</strong>
                      <span>退款数量</span>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
        `)[0]
        )
      })
      $parent.html(fragment)
    },

    // 渲染联系方式
    renderContact: function (infos) {
      const $managerWrapper = $('.manager-wrapper')
      const managerObjs = infos.parent_user_info

      const $myContact = $('.my-contact-number')

      // render manager
      $managerWrapper
        .find('.manager-pic')
        .html(
          $(`<img src="${window.location.origin}${managerObjs.avatar}" />`)[0]
        )
      $managerWrapper
        .find('.manager-infos__name strong')
        .text(managerObjs.username)

      const $msp = $('.manager-number-box')
      $msp.find('.manager-qq-number').text(managerObjs.qq ?? '无')
      $msp.find('.manager-wx-number').text(managerObjs.weixin ?? '无')
      $msp
        .find('.manager-qq-number-icon')
        .attr('data-value', managerObjs.qq ?? '无')
      $msp
        .find('.manager-wx-number-icon')
        .attr('data-value', managerObjs.weixin ?? '无')

      // render me
      $myContact.find('.my-qq-number').text(infos.qq ?? '无')
      $myContact.find('.my-wx-number').text(infos.weixin ?? '无')
      $myContact.find('.my-qq-number-icon').attr('data-value', infos.qq ?? '无')
      $myContact
        .find('.my-wx-number-icon')
        .attr('data-value', infos.weixin ?? '无')

      $('.manager-container').on('click', 'i.pear-icon-copy', function () {
        const value = $($(this).context).attr('data-value')
        if (value !== '无') {
          copyText(value)
        } else {
          layer.msg('暂无无联系方式')
        }
      })
    },

    // 渲染顶部会员信息
    renderMemberInfo: function (infos) {
      const $box = $('#memberinfo')
      $box
        .find('.logo')
        .html($(`<img src="${window.location.origin}${infos.avatar}" />`)[0])
      $box.find('h3').text(infos.nickname)
      $box.find('span:eq(1)').text(infos.created_at)
    },

    // 渲染外部链接 (可被复制)
    renderOutsideLink: function (linkInfo) {
      if (linkInfo) {
        const { link } = linkInfo
        $('#setlink').text(link)
        $('#setlink').on('click', function () {
          window.open(link)
        })
        $('#copy-url').on('click', function () {
          copyText(link)
        })
      }
    },

    renderMoney(infos) {
      const { money = 0, commission = 0, invitation_total = 0, money_recharge = 0} = infos
      const count = layui.count

      console.log(infos,'infos');
      console.log(invitation_total,'invitation_total');

      if (money > 100) {
        count.up('card2-value', {
          time: 4000,
          num: parseFloat(money, 2),
          bit: 2,
          regulator: 50,
        })
      } else $('#card2-value').text(money)

      if (commission > 100) {
        count.up('card3-value', {
          time: 60,
          num: parseFloat(commission, 2),
          bit: 0,
          regulator: 2,
        })
      } else $('#card3-value').text(commission)

      if (invitation_total > 100) {
        count.up('card4-value', {
          time: 60,
          num: parseInt(invitation_total),
          bit: 0,
          regulator: 2,
        })
      } else $('#card4-value').text(invitation_total)

      if (money_recharge > 100) {
        count.up('card5-value', {
          time: 60,
          num: parseFloat(money_recharge,2),
          bit: 0,
          regulator: 2,
        })
      } else $('#card5-value').text(money_recharge)
    },
  }
}

/**
 * 初始化 首页 & 渲染操作
 */
const initializationIndexInfo = function () {
  const customIndexModify = CustomIndexModify()
  const that = customIndexModify
  that.getInfo(function (infos) {
    that.renderMoney(infos)

    // 渲染节点购买信息
    that.renderNodesInfo(infos.user_extend, infos)
    that.renderContact(infos)
    that.renderMemberInfo(infos)

    // 渲染外部链接
    that.renderOutsideLink(infos.link_info)

    // 执行渲染
    console.log('%c 首页基础信息 >>>', 'background: blue; color: #fff', infos)
    myPriceTables = infos.user_extend
  })
}

const updateMyContact = function (callback) {
  const $ = layui.$
  const qqval = $($('.set-my-contact').find('form input:eq(0)')[0]).val()
  const wxval = $($('.set-my-contact').find('form input:eq(1)')[0]).val()
  // 编辑会员信息
  const URL = `/app/admin/v1-api/editUserInfo?qq=${qqval}&weixin=${wxval}`

  layer.load()
  $.ajax({
    url: URL,
    success: function (res) {
      layer.closeAll('loading')
      layer.msg(res.msg)
      if (res.code) return

      callback &&
        callback({
          qq: qqval,
          wx: wxval,
        })
    },
  })
}
